package business

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"

    "crypto/tls"
    keycloakClient "git.inspur.com/x/keycloak"
    "git.inspur.com/x/keycloak/resource"
)

func GetIamPublicKey(config *keycloakClient.Config) (string, error) {
    realmUrl := fmt.Sprintf("%s/realms/%s", config.Host, config.Realm)

    cli := http.Client{}
    cli.Transport = &http.Transport{
        TLSClientConfig: &tls.Config{
            InsecureSkipVerify: false,
        },
    }
    logger.Debug("realmUrl: %s", realmUrl)
    resp, err := cli.Get(realmUrl)
    if err != nil {
        return "", err
    }

    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    var realmInfo resource.RealmInfo
    err = json.Unmarshal(body, &realmInfo)
    if err != nil {
        return "", err
    }

    return realmInfo.PublicKey, nil
}
